import edge_tts
from abc import abstractmethod

from .utils import logger

class BaseTTS:
    def __init__(self):
        self.name = "base_tts"

    # 语音生成的核心方法，抽象函数
    @abstractmethod
    def get_audio(self, text, save_path):
        """
            text: 待转化文本
            save_path: 音频保存路径，这里应该是一个临时文件，上传到OSS后会删除

            return: 保存的音频文件路径
        """
        raise NotImplementedError('Please implemented get_audio function.')

    def __call__(self, text, save_path):
        return self.get_audio(text, save_path)

class EdgeTTS(BaseTTS):
    def __init__(self, voice_id="zh-CN-XiaoxiaoNeural", speed=0.0, vol=0.0, pitch=0.0):
        super(EdgeTTS, self).__init__()
        self.name = "edge_tts"
        self.voice_id = voice_id
        self.rate = speed
        self.volume = vol
        self.pitch = pitch

    async def atts(self, text, save_path, ratestr, volstr, pitchstr):
        communicate = edge_tts.Communicate(text, self.voice_id, rate=ratestr, volume=volstr, pitch=pitchstr)
        await communicate.save(save_path)

    async def get_audio(self, text, save_path):   
        #使用edge-tts把文字转成音频
        if self.rate>=0:
            ratestr=f"+{int(self.rate)}%"
        elif self.rate<0:
            ratestr=f"{int(self.rate)}%"
        if self.volume >= 0:
            volstr=f"+{int(self.volume)}%"
        elif self.volume<0:
            volstr=f"{int(self.volume)}%"
        if self.pitch >= 0:
            pitchstr=f"+{int(self.pitch)}Hz"
        elif self.pitch<0:
            pitchstr=f"{int(self.pitch)}Hz"
        for _ in range(3):
            logger.info(f"EdgeTTS -- voice_id:{self.voice_id} | save_path:{save_path}")
            try:
                text = text.replace("*", "").replace(".", " ").replace("#", " ").replace("-", " ")
                await self.atts(text=text, save_path=save_path, ratestr=ratestr, volstr=volstr, pitchstr=pitchstr)
                return save_path
            except Exception as e:
                logger.error(f"EdgeTTS: {e}")
        return None

    async def __call__(self, text, save_path):
        return await self.get_audio(text, save_path)

if __name__ == '__main__':
    text = """你好啊，很高兴认识你。"""
    audio_path = f"tmp/test.mp3"
    tts_fun = EdgeTTS()
    audio_file = tts_fun(text, audio_path)
    print(audio_file)
